import { setToken, getToken, removeToken } from '@/utils/cookies'
import { resetRouter } from '@/router'
import { login, getUserInfo } from '@/api/user'


interface State {
  token: string,
  user_id: string | number,
  user_info: {[key: string]: any},
  roles: string[],
}

interface Mutations<S = State> {
  MUTATIONS_SET_TOKEN (state: S, token: string): void
  MUTATIONS_SET_USER_ID (state: S, user_id: string | number): void
  MUTATIONS_SET_USER_INFO (state: S, user_info: {[key: string]: any}): void
  MUTATIONS_SET_ROLES (state: S, roles: string[]): void
}

interface ActionContext {
  commit<K extends keyof Mutations>(
      key: K,
      payload ?: Parameters<Mutations[K]>[1],
  ): ReturnType<Mutations[K]>
}

interface Actions {
  ACTION_LOGIN ({ commit }: ActionContext, userInfo: { user_name: string, password: string | number}): void
  ACTION_USER_INFO ({ commit }: ActionContext): void
  ACTION_RESET_TOKEN ({ commit }: ActionContext): void
  ACTION_LOGIN_OUT ({ commit }: ActionContext): void
}

const state: State= {
  token: getToken() || '',
  user_id: 0,
  user_info: {},
  roles: [],
};

const mutations: Mutations = {
  MUTATIONS_SET_TOKEN (state, token) {
      state.token = token
      setToken(token)
  },
  MUTATIONS_SET_USER_ID (state, user_id) {
    state.user_id = user_id
  },
  MUTATIONS_SET_USER_INFO (state, user_info) {
    state.user_info = user_info
  },
  MUTATIONS_SET_ROLES (state, roles) {
    state.roles = roles
  },
}

const actions: Actions = {
  // 登录
  async ACTION_LOGIN ({ commit }, userInfo: { user_name: string, password: string | number}) {
    const res = await login(userInfo)  // 登录 api
    try {
      if(res.code == 200 ) {
        const { token } = res.data
        setToken(token)
        commit('MUTATIONS_SET_TOKEN', token)
      }
      return Promise.resolve(res)
    } catch (error) {
      return Promise.reject(error)
    }
    
    //  临时token
    // commit('MUTATIONS_SET_TOKEN', 'f4fdb2b935d5e7a1')
  },
  

  // 获取 user_info
  async ACTION_USER_INFO ({ commit }) {
    if (state.token === '') {
      throw Error('获取用户信息: token is undefined!')
    }
    const res = await getUserInfo()  // 获取user_info api
    try {
      if(res.code == 200 ) {
        const { mg_id } = res.data
        commit('MUTATIONS_SET_USER_ID', mg_id)
        commit('MUTATIONS_SET_USER_INFO', res.data)
        // if (!roles || roles.length == 0) {
        //   throw Error('获取用户信息: roles is null as array!')
        // }
        commit('MUTATIONS_SET_ROLES', ['admin'])
        return Promise.resolve(res)
      }
    } catch (error) {
      return Promise.reject(error)
    }
    
    //  临时用户信息数据
    // commit('MUTATIONS_SET_USER_INFO',{
    //   user_id: '1',
    //   mg_name: 'admin',
    //   roles: ['admin'],
    // })
    // // commit('MUTATIONS_SET_USER_ID', '1')
    // commit('MUTATIONS_SET_ROLES', ['admin'])
  },

  // 清除token
  async ACTION_RESET_TOKEN ({ commit }) {
    commit('MUTATIONS_SET_TOKEN', '')
    commit('MUTATIONS_SET_ROLES', [])
    removeToken()
    return Promise.resolve('')
  },

  // 退出登录
  async ACTION_LOGIN_OUT ({ commit }) {   
    commit('MUTATIONS_SET_TOKEN', '')
    commit('MUTATIONS_SET_USER_ID', 0)
    commit('MUTATIONS_SET_ROLES', [])
    removeToken()
    resetRouter()
    return Promise.resolve('')
  },
};

export default {
	namespaced: true,
	state,
	mutations,
	actions
};